<?php

namespace App\Admin\Actions\Keyword;

use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Add extends Action
{
    protected $selector = '.add';

    public function handle(Request $request)
    {
        $keywords = explode(',', $request->input('keywords'));
        $prefix = $request->input('prefix') ?
            json_encode(explode(',', $request->input('prefix'))) :
            '[""]';
        $suffix = $request->input('suffix') ?
            json_encode(explode(',', $request->input('suffix'))) :
            '[""]';

        $insertData = [];
        foreach ($keywords as $keyword) {
            $insertData[] = [
                'keyword' => $keyword,
                'prefix' => $prefix,
                'suffix' => $suffix,
                'created_at' => now(),
                'updated_at' => now()
            ];
        }

        DB::table('keywords')->insertOrIgnore($insertData);

        return $this->response()->success('批量添加成功')->refresh();
    }

    public function form()
    {
        $this->text('keywords', '关键词')->help('多个关键词使用","分隔');
        $this->text('prefix', '词头')
            ->value(str_replace(PHP_EOL, ',', config('keyword.default_prefix')));
        $this->text('suffix', '词尾')
            ->value(str_replace(PHP_EOL, ',', config('keyword.default_suffix')));
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-success add">添加关键词</a>
HTML;
    }
}
